<template>
  <div class="nav-menu">
    <!-- 头像+文字 -->
    <div class="top-area">
      <img class="top-img" src="../../../assets/img/logo.svg" alt="" />
      <span v-if="!menuStatus" class="title">TS-Vue3</span>
    </div>

    <!-- 菜单区域 -->
    <el-menu
      :default-active="String(activeIndex)"
      class="el-menu-vertical-demo"
      :collapse="menuStatus"
      background-color="#001322"
      text-color="#fff"
      unique-opened
      collapse-transition
    >
      <template v-for="item in userMenus" :key="item.id">
        <el-sub-menu :index="String(item.id)">
          <template #title>
            <el-icon><component :is="item.icon.slice(8)"></component></el-icon>
            <span>{{ item.name }}</span>
          </template>
          <template v-if="item.type == '1'">
            <el-menu-item
              @click="changeRouter(item.name, subItem)"
              v-for="subItem in item.children"
              :key="subItem.id"
              :index="'' + subItem.id"
              >{{ subItem.name }}</el-menu-item
            >
          </template>
        </el-sub-menu>
      </template>
    </el-menu>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref } from "vue"
import { useStore } from "vuex"
import router from "@/router/index"
import { IRootWithModel, IUserMenu } from "@/types/userType"
import { useRoute } from "vue-router"
import { getIdByPath } from "@/utils/map-menus"
export default defineComponent({
  props: {
    menuStatus: {
      type: Boolean,
      default: true,
    },
  },
  setup() {
    const store = useStore<IRootWithModel>()
    const userMenus = computed(() => store.state.login.userMenu)
    const changeRouter = (fathername: string, subItem: IUserMenu) => {
      router.push(subItem.url)
      store.commit("changeUserMenu", [
        fathername,
        subItem.name,
        subItem.children?.name,
      ])
    }
    // 获取当前路由对象
    const route = useRoute()
    // 获取当前路径
    const currentPath = route.path
    // 获取当前被激活的菜单id
    const activeIndex = getIdByPath(userMenus.value, currentPath)
    return {
      userMenus,
      changeRouter,
      activeIndex,
    }
  },
})
</script>
<style lang="less" scoped>
.top-area {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 70px;
  overflow: hidden;
}
.top-img {
  width: 30px;
  margin-left: 15px;
}
.title {
  line-height: 70px;
  color: #fff;
}
.el-menu-item {
  background: #071d2e;
}
.el-menu {
  border-right: none;
}
</style>
